#include "ws2812.h"
#include <esp_log.h>
#include <esp_random.h>
#include <esp_timer.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <cmath>
#include <algorithm>

static const char* TAG = "WS2812";

// 配置常量
#define LED_STRIP_RMT_RES_HZ  (10 * 1000 * 1000)  // 10MHz resolution
#define LED_STRIP_USE_DMA     0                    // 根据芯片能力调整

// ==================== 颜色常量定义 ====================
const WS2812::Color WS2812::Color::BLACK(0, 0, 0);
const WS2812::Color WS2812::Color::WHITE(255, 255, 255);
const WS2812::Color WS2812::Color::RED(255, 0, 0);
const WS2812::Color WS2812::Color::GREEN(0, 255, 0);
const WS2812::Color WS2812::Color::BLUE(0, 0, 255);
const WS2812::Color WS2812::Color::YELLOW(255, 255, 0);
const WS2812::Color WS2812::Color::CYAN(0, 255, 255);
const WS2812::Color WS2812::Color::MAGENTA(255, 0, 255);
const WS2812::Color WS2812::Color::ORANGE(255, 165, 0);
const WS2812::Color WS2812::Color::PURPLE(128, 0, 128);
const WS2812::Color WS2812::Color::PINK(255, 192, 203);

// ==================== 颜色运算符实现 ====================

WS2812::Color WS2812::Color::operator+(const Color& other) const {
    return Color(
        std::min(255, static_cast<int>(red) + other.red),
        std::min(255, static_cast<int>(green) + other.green),
        std::min(255, static_cast<int>(blue) + other.blue)
    );
}

WS2812::Color WS2812::Color::operator*(float factor) const {
    return Color(
        static_cast<uint8_t>(std::min(255.0f, red * factor)),
        static_cast<uint8_t>(std::min(255.0f, green * factor)),
        static_cast<uint8_t>(std::min(255.0f, blue * factor))
    );
}

WS2812::Color WS2812::Color::operator-(const Color& other) const {
    return Color(
        static_cast<uint8_t>(std::max(0, static_cast<int>(red) - other.red)),
        static_cast<uint8_t>(std::max(0, static_cast<int>(green) - other.green)),
        static_cast<uint8_t>(std::max(0, static_cast<int>(blue) - other.blue))
    );
}

bool WS2812::Color::operator==(const Color& other) const {
    return red == other.red && green == other.green && blue == other.blue;
}

bool WS2812::Color::operator!=(const Color& other) const {
    return !(*this == other);
}

// ==================== 构造函数和析构函数 ====================

WS2812::WS2812(int gpio_pin, int led_count) 
    : gpio_pin_(gpio_pin)
    , led_count_(led_count)
    , led_strip_(nullptr)
    , brightness_(100)
    , is_initialized_(false)
    , current_animation_(AnimationType::NONE)
    , animation_running_(false)
    , animation_paused_(false) {
    
    ESP_LOGI(TAG, "WS2812创建: GPIO%d, %d个LED", gpio_pin, led_count);
    
    // 初始化颜色状态数组
    current_colors_.resize(led_count, Color::BLACK);
}

WS2812::~WS2812() {
    // 停止动画
    StopAnimation();
    
    // 清理LED资源
    if (led_strip_) {
        led_strip_del(led_strip_);
        led_strip_ = nullptr;
    }
    
    ESP_LOGI(TAG, "WS2812销毁完成");
}

// ==================== 移动语义实现 ====================

WS2812::WS2812(WS2812&& other) noexcept
    : gpio_pin_(other.gpio_pin_)
    , led_count_(other.led_count_)
    , led_strip_(other.led_strip_)
    , brightness_(other.brightness_)
    , is_initialized_(other.is_initialized_)
    , current_animation_(other.current_animation_)
    , animation_running_(other.animation_running_)
    , animation_paused_(other.animation_paused_)
    , current_colors_(std::move(other.current_colors_)) {
    
    // 清空源对象
    other.led_strip_ = nullptr;
    other.is_initialized_ = false;
    other.animation_running_ = false;
}

WS2812& WS2812::operator=(WS2812&& other) noexcept {
    if (this != &other) {
        // 清理当前资源
        StopAnimation();
        if (led_strip_) {
            led_strip_del(led_strip_);
        }
        
        // 移动资源
        gpio_pin_ = other.gpio_pin_;
        led_count_ = other.led_count_;
        brightness_ = other.brightness_;
        is_initialized_ = other.is_initialized_;
        led_strip_ = other.led_strip_;
        current_animation_ = other.current_animation_;
        animation_running_ = other.animation_running_;
        animation_paused_ = other.animation_paused_;
        current_colors_ = std::move(other.current_colors_);
        
        // 清空源对象
        other.led_strip_ = nullptr;
        other.is_initialized_ = false;
        other.animation_running_ = false;
    }
    return *this;
}

// ==================== 基本操作实现 ====================

esp_err_t WS2812::Initialize() {
    if (is_initialized_) {
        ESP_LOGW(TAG, "WS2812已初始化");
        return ESP_OK;
    }

    ESP_LOGI(TAG, "初始化WS2812: GPIO%d, %d个LED", gpio_pin_, led_count_);

    // LED strip通用配置
    led_strip_config_t strip_config = {
        .strip_gpio_num = gpio_pin_,
        .max_leds = static_cast<uint32_t>(led_count_),
        .led_model = LED_MODEL_WS2812,
        .color_component_format = LED_STRIP_COLOR_COMPONENT_FMT_GRB,
        .flags = {
            .invert_out = false,
        }
    };

    // RMT后端配置
    led_strip_rmt_config_t rmt_config = {
        .clk_src = RMT_CLK_SRC_DEFAULT,
        .resolution_hz = LED_STRIP_RMT_RES_HZ,
        .mem_block_symbols = 0, // 让驱动自动选择
        .flags = {
            .with_dma = LED_STRIP_USE_DMA,
        }
    };

    esp_err_t ret = led_strip_new_rmt_device(&strip_config, &rmt_config, &led_strip_);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "创建LED灯带失败: %s", esp_err_to_name(ret));
        return ret;
    }

    is_initialized_ = true;
    ESP_LOGI(TAG, "WS2812初始化成功");
    
    // 清除所有LED
    ret = Clear();
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "初始化清除LED失败: %s", esp_err_to_name(ret));
    }
    
    return ret;
}

esp_err_t WS2812::ValidateIndex(int index) const {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    if (index < 0 || index >= led_count_) {
        ESP_LOGE(TAG, "LED索引%d超出范围[0, %d)", index, led_count_);
        return ESP_ERR_INVALID_ARG;
    }

    return ESP_OK;
}

esp_err_t WS2812::SetPixelInternal(int index, const Color& color, bool refresh) {
    esp_err_t ret = ValidateIndex(index);
    if (ret != ESP_OK) {
        return ret;
    }

    // 保存原始颜色到状态数组
    current_colors_[index] = color;
    
    // 应用亮度调整
    Color adjusted_color = ApplyBrightness(color);
    
    // 设置LED颜色
    ret = led_strip_set_pixel(led_strip_, index, 
                             adjusted_color.red, 
                             adjusted_color.green, 
                             adjusted_color.blue);
    
    // 根据参数决定是否自动刷新
    if (ret == ESP_OK && refresh) {
        ret = led_strip_refresh(led_strip_);
    }
    
    return ret;
}

esp_err_t WS2812::SetPixel(int index, const Color& color) {
    return SetPixelInternal(index, color, true);
}

esp_err_t WS2812::SetPixel(int index, uint8_t red, uint8_t green, uint8_t blue) {
    return SetPixel(index, Color(red, green, blue));
}

esp_err_t WS2812::SetPixelNoRefresh(int index, const Color& color) {
    return SetPixelInternal(index, color, false);
}

esp_err_t WS2812::SetPixelNoRefresh(int index, uint8_t red, uint8_t green, uint8_t blue) {
    return SetPixelNoRefresh(index, Color(red, green, blue));
}

esp_err_t WS2812::SetPixelsNoRefresh(const std::vector<Color>& colors, int start_index) {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    if (start_index < 0 || start_index >= led_count_) {
        ESP_LOGE(TAG, "起始索引%d超出范围", start_index);
        return ESP_ERR_INVALID_ARG;
    }

    int end_index = std::min(start_index + static_cast<int>(colors.size()), led_count_);
    esp_err_t ret = ESP_OK;

    for (int i = start_index; i < end_index; i++) {
        int color_index = i - start_index;
        esp_err_t pixel_ret = SetPixelInternal(i, colors[color_index], false);
        if (pixel_ret != ESP_OK) {
            ret = pixel_ret;
        }
    }

    return ret;
}

esp_err_t WS2812::SetAllPixels(const Color& color) {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    // 保存原始颜色到所有像素
    std::fill(current_colors_.begin(), current_colors_.end(), color);

    // 应用亮度调整并设置所有像素
    Color adjusted_color = ApplyBrightness(color);
    
    esp_err_t ret = ESP_OK;
    for (int i = 0; i < led_count_; i++) {
        esp_err_t pixel_ret = led_strip_set_pixel(led_strip_, i, 
                                                 adjusted_color.red, 
                                                 adjusted_color.green, 
                                                 adjusted_color.blue);
        if (pixel_ret != ESP_OK) {
            ret = pixel_ret;
            ESP_LOGW(TAG, "设置LED[%d]失败: %s", i, esp_err_to_name(pixel_ret));
        }
    }
    
    // 自动刷新显示
    if (ret == ESP_OK) {
        ret = led_strip_refresh(led_strip_);
        if (ret != ESP_OK) {
            ESP_LOGE(TAG, "刷新显示失败: %s", esp_err_to_name(ret));
        }
    }
    
    return ret;
}

esp_err_t WS2812::Clear() {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    // 清除颜色状态
    std::fill(current_colors_.begin(), current_colors_.end(), Color::BLACK);

    esp_err_t ret = led_strip_clear(led_strip_);
    if (ret == ESP_OK) {
        ret = led_strip_refresh(led_strip_);
        if (ret != ESP_OK) {
            ESP_LOGE(TAG, "清除后刷新失败: %s", esp_err_to_name(ret));
        }
    } else {
        ESP_LOGE(TAG, "硬件清除失败: %s", esp_err_to_name(ret));
    }
    return ret;
}

esp_err_t WS2812::Refresh() {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    esp_err_t ret = led_strip_refresh(led_strip_);
    return ret;
}

// ==================== 亮度控制实现 ====================

esp_err_t WS2812::SetBrightness(uint8_t brightness) {
    // 参数验证和调整
    if (brightness > 100) {
        ESP_LOGW(TAG, "亮度%d超过最大值100，已调整", brightness);
        brightness = 100;
    }
    
    // 检查是否需要更新
    if (brightness_ == brightness) {
        return ESP_OK;
    }
    
    brightness_ = brightness;
    
    // 如果已初始化，立即应用新的亮度设置
    if (is_initialized_) {
        RefreshWithCurrentColors();
    }
    
    return ESP_OK;
}

WS2812::Color WS2812::GetPixelColor(int index) const {
    if (index < 0 || index >= led_count_) {
        ESP_LOGW(TAG, "索引%d超出范围，返回黑色", index);
        return Color::BLACK;
    }
    
    return current_colors_[index];
}

void WS2812::RefreshWithCurrentColors() {
    // 重新设置所有像素以应用新的亮度
    for (int i = 0; i < led_count_; i++) {
        Color adjusted_color = ApplyBrightness(current_colors_[i]);
        led_strip_set_pixel(led_strip_, i, 
                           adjusted_color.red, 
                           adjusted_color.green, 
                           adjusted_color.blue);
    }
    // 直接刷新显示
    led_strip_refresh(led_strip_);
}

// ==================== 动画效果实现 ====================

esp_err_t WS2812::FadeIn(const Color& color, uint32_t duration_ms) {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    // 参数验证
    if (duration_ms == 0) {
        ESP_LOGW(TAG, "淡入动画持续时间为0，跳过执行");
        return ESP_OK;
    }

    current_animation_ = AnimationType::FADE_IN;
    animation_running_ = true;
    animation_paused_ = false;
    
    // 优化步数计算：根据持续时间动态调整
    const int min_steps = 20;   // 最少步数，保证基本流畅度
    const int max_steps = 100;  // 最大步数，避免过度计算
    const int optimal_step_time = 20; // 目标每步20ms
    
    int steps = std::max(min_steps, std::min(max_steps, static_cast<int>(duration_ms / optimal_step_time)));
    const uint32_t step_delay = duration_ms / steps;
    
    uint32_t last_time = esp_timer_get_time() / 1000;
    
    for (int step = 0; step <= steps && animation_running_; step++) {
        // 检查暂停状态
        while (animation_paused_ && animation_running_) {
            vTaskDelay(pdMS_TO_TICKS(10));
            // 暂停期间更新时间基准
            last_time = esp_timer_get_time() / 1000;
        }
        
        if (!animation_running_) break;
        
        // 使用平滑的淡入曲线（ease-in）
        float progress = static_cast<float>(step) / steps;
        float factor = progress * progress; // 二次方缓入
        
        Color fade_color = color * factor;
        SetAllPixels(fade_color);
        
        // 精确时间控制
        uint32_t current_time = esp_timer_get_time() / 1000;
        uint32_t elapsed = current_time - last_time;
        
        if (elapsed < step_delay) {
            uint32_t remaining_delay = step_delay - elapsed;
            vTaskDelay(pdMS_TO_TICKS(remaining_delay));
        }
        
        last_time = esp_timer_get_time() / 1000;
    }
    
    animation_running_ = false;
    current_animation_ = AnimationType::NONE;
    return ESP_OK;
}

esp_err_t WS2812::FadeOut(uint32_t duration_ms) {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    // 参数验证
    if (duration_ms == 0) {
        ESP_LOGW(TAG, "淡出动画持续时间为0，跳过执行");
        return ESP_OK;
    }

    current_animation_ = AnimationType::FADE_OUT;
    animation_running_ = true;
    animation_paused_ = false;
    
    // 获取当前平均颜色作为起始颜色
    Color start_color = Color::BLACK;
    if (!current_colors_.empty()) {
        uint32_t total_r = 0, total_g = 0, total_b = 0;
        for (const auto& color : current_colors_) {
            total_r += color.red;
            total_g += color.green;
            total_b += color.blue;
        }
        start_color = Color(
            total_r / current_colors_.size(),
            total_g / current_colors_.size(),
            total_b / current_colors_.size()
        );
    }
    
    // 优化步数计算：根据持续时间动态调整
    const int min_steps = 20;   // 最少步数，保证基本流畅度
    const int max_steps = 100;  // 最大步数，避免过度计算
    const int optimal_step_time = 20; // 目标每步20ms
    
    int steps = std::max(min_steps, std::min(max_steps, static_cast<int>(duration_ms / optimal_step_time)));
    const uint32_t step_delay = duration_ms / steps;
    
    uint32_t last_time = esp_timer_get_time() / 1000;
    
    for (int step = 0; step <= steps && animation_running_; step++) {
        // 检查暂停状态
        while (animation_paused_ && animation_running_) {
            vTaskDelay(pdMS_TO_TICKS(10));
            // 暂停期间更新时间基准
            last_time = esp_timer_get_time() / 1000;
        }
        
        if (!animation_running_) break;
        
        // 使用平滑的淡出曲线（ease-out）
        float progress = static_cast<float>(step) / steps;
        float factor = 1.0f - (progress * progress); // 二次方缓出
        
        Color fade_color = start_color * factor;
        SetAllPixels(fade_color);
        
        // 精确时间控制
        uint32_t current_time = esp_timer_get_time() / 1000;
        uint32_t elapsed = current_time - last_time;
        
        if (elapsed < step_delay) {
            uint32_t remaining_delay = step_delay - elapsed;
            vTaskDelay(pdMS_TO_TICKS(remaining_delay));
        }
        
        last_time = esp_timer_get_time() / 1000;
    }
    
    animation_running_ = false;
    current_animation_ = AnimationType::NONE;
    return ESP_OK;
}

esp_err_t WS2812::Breathe(const Color& color, uint32_t period_ms, uint32_t cycles) {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    // 参数验证
    if (period_ms == 0) {
        ESP_LOGW(TAG, "呼吸动画周期为0，跳过执行");
        return ESP_OK;
    }

    current_animation_ = AnimationType::BREATHE;
    animation_running_ = true;
    animation_paused_ = false;
    
    // 优化步数计算：根据周期时间动态调整
    const int min_steps = 30;   // 最少步数，保证基本流畅度
    const int max_steps = 120;  // 最大步数，避免过度计算
    const int optimal_step_time = 20; // 目标每步20ms
    
    int steps_per_half_cycle = std::max(min_steps, std::min(max_steps, static_cast<int>(period_ms / (2 * optimal_step_time))));
    const uint32_t step_delay = period_ms / (2 * steps_per_half_cycle);
    
    uint32_t cycle_count = 0;
    uint32_t last_time = esp_timer_get_time() / 1000;
    
    while (animation_running_ && (cycles == 0 || cycle_count < cycles)) {
        // 完整的呼吸周期：0 -> 1 -> 0
        for (int step = 0; step < steps_per_half_cycle * 2 && animation_running_; step++) {
            // 检查暂停状态
            while (animation_paused_ && animation_running_) {
                vTaskDelay(pdMS_TO_TICKS(10));
                // 暂停期间更新时间基准
                last_time = esp_timer_get_time() / 1000;
            }
            
            if (!animation_running_) break;
            
            // 使用正弦函数创建平滑的呼吸效果
            float phase = (static_cast<float>(step) / steps_per_half_cycle) * M_PI;
            float brightness_factor = (sin(phase) + 1.0f) * 0.5f; // 0.0 到 1.0
            
            // 应用最小亮度，避免完全熄灭
            brightness_factor = 0.1f + brightness_factor * 0.9f; // 0.1 到 1.0
            
            Color breathe_color = color * brightness_factor;
            SetAllPixels(breathe_color);
            
            // 精确时间控制
            uint32_t current_time = esp_timer_get_time() / 1000;
            uint32_t elapsed = current_time - last_time;
            
            if (elapsed < step_delay) {
                uint32_t remaining_delay = step_delay - elapsed;
                vTaskDelay(pdMS_TO_TICKS(remaining_delay));
            }
            
            last_time = esp_timer_get_time() / 1000;
        }
        
        cycle_count++;
    }
    
    animation_running_ = false;
    current_animation_ = AnimationType::NONE;
    return ESP_OK;
}

esp_err_t WS2812::ColorWipe(const Color& color, uint32_t delay_ms) {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    // 参数验证
    if (delay_ms == 0) {
        ESP_LOGW(TAG, "颜色擦除延迟为0，使用默认值50ms");
        delay_ms = 50;
    }

    current_animation_ = AnimationType::COLOR_WIPE;
    animation_running_ = true;
    animation_paused_ = false;
    
    uint32_t last_time = esp_timer_get_time() / 1000;
    
    for (int i = 0; i < led_count_ && animation_running_; i++) {
        // 检查暂停状态
        while (animation_paused_ && animation_running_) {
            vTaskDelay(pdMS_TO_TICKS(10));
            // 暂停期间更新时间基准
            last_time = esp_timer_get_time() / 1000;
        }
        
        if (!animation_running_) break;
        
        // 设置当前LED颜色
        esp_err_t ret = SetPixel(i, color);
        if (ret != ESP_OK) {
            ESP_LOGW(TAG, "设置LED[%d]失败: %s", i, esp_err_to_name(ret));
        }
        
        // 精确时间控制
        uint32_t current_time = esp_timer_get_time() / 1000;
        uint32_t elapsed = current_time - last_time;
        
        if (elapsed < delay_ms) {
            uint32_t remaining_delay = delay_ms - elapsed;
            vTaskDelay(pdMS_TO_TICKS(remaining_delay));
        }
        
        last_time = esp_timer_get_time() / 1000;
    }
    
    animation_running_ = false;
    current_animation_ = AnimationType::NONE;
    return ESP_OK;
}

esp_err_t WS2812::Sparkle(const Color& color, uint32_t duration_ms, uint8_t density) {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    // 参数验证
    if (duration_ms == 0) {
        ESP_LOGW(TAG, "闪烁动画持续时间为0，跳过执行");
        return ESP_OK;
    }
    
    if (density == 0 || density > 100) {
        ESP_LOGW(TAG, "闪烁密度%d无效，使用默认值10", density);
        density = 10;
    }

    current_animation_ = AnimationType::SPARKLE;
    animation_running_ = true;
    animation_paused_ = false;
    
    // 保存当前状态
    std::vector<Color> original_colors = current_colors_;
    
    // 优化闪烁参数
    const uint32_t sparkle_interval = 80;  // 闪烁间隔80ms
    const uint32_t sparkle_duration = 40;  // 单次闪烁持续40ms
    const int max_sparkles = std::min(static_cast<int>(led_count_ * density / 100), led_count_);
    
    uint32_t start_time = esp_timer_get_time() / 1000;
    uint32_t last_sparkle_time = start_time;
    
    // 活跃闪烁LED跟踪
    std::vector<int> active_sparkles;
    std::vector<uint32_t> sparkle_start_times;
    
    while (animation_running_) {
        // 检查暂停状态
        while (animation_paused_ && animation_running_) {
            vTaskDelay(pdMS_TO_TICKS(10));
            // 暂停期间更新时间基准
            start_time = esp_timer_get_time() / 1000;
            last_sparkle_time = start_time;
        }
        
        if (!animation_running_) break;
        
        uint32_t current_time = esp_timer_get_time() / 1000;
        
        // 检查是否超过总持续时间
        if (current_time - start_time >= duration_ms) {
            break;
        }
        
        // 移除过期的闪烁
        for (int i = active_sparkles.size() - 1; i >= 0; i--) {
            if (current_time - sparkle_start_times[i] >= sparkle_duration) {
                // 恢复原始颜色
                SetPixelNoRefresh(active_sparkles[i], original_colors[active_sparkles[i]]);
                active_sparkles.erase(active_sparkles.begin() + i);
                sparkle_start_times.erase(sparkle_start_times.begin() + i);
            }
        }
        
        // 添加新的闪烁
        if (current_time - last_sparkle_time >= sparkle_interval && 
            static_cast<int>(active_sparkles.size()) < max_sparkles) {
            
            // 随机选择未闪烁的LED
            int attempts = 0;
            while (attempts < 10 && static_cast<int>(active_sparkles.size()) < max_sparkles) {
                int random_led = esp_random() % led_count_;
                
                // 检查是否已经在闪烁
                bool already_sparkling = false;
                for (int active_led : active_sparkles) {
                    if (active_led == random_led) {
                        already_sparkling = true;
                        break;
                    }
                }
                
                if (!already_sparkling) {
                    // 添加随机亮度变化，使闪烁更自然
                    float brightness_factor = 0.7f + (esp_random() % 31) / 100.0f; // 0.7-1.0
                    Color sparkle_color = color * brightness_factor;
                    
                    SetPixelNoRefresh(random_led, sparkle_color);
                    active_sparkles.push_back(random_led);
                    sparkle_start_times.push_back(current_time);
                }
                attempts++;
            }
            
            last_sparkle_time = current_time;
        }
        
        // 统一刷新显示
        Refresh();
        vTaskDelay(pdMS_TO_TICKS(10)); // 减少CPU占用
    }
    
    // 恢复原始状态
    current_colors_ = original_colors;
    RefreshWithCurrentColors();
    
    animation_running_ = false;
    current_animation_ = AnimationType::NONE;
    return ESP_OK;
}

esp_err_t WS2812::Rainbow(uint32_t duration_ms) {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    // 参数验证
    if (duration_ms == 0) {
        ESP_LOGW(TAG, "彩虹动画持续时间为0，跳过执行");
        return ESP_OK;
    }

    current_animation_ = AnimationType::RAINBOW;
    animation_running_ = true;
    animation_paused_ = false;
    
    // 优化步数计算：根据持续时间动态调整，确保流畅度
    const int min_steps = 60;   // 最少步数，保证基本流畅度
    const int max_steps = 360;  // 最大步数，避免过度计算
    const int optimal_step_time = 16; // 目标每步16ms（约60fps）
    
    int steps = std::max(min_steps, std::min(max_steps, static_cast<int>(duration_ms / optimal_step_time)));
    const uint32_t step_delay = duration_ms / steps;
    
    // 预计算颜色偏移量，避免重复计算
    const float hue_step = 360.0f / steps;
    const float led_hue_offset = 360.0f / led_count_;
    
    uint32_t last_time = esp_timer_get_time() / 1000;
    
    for (int j = 0; j < steps && animation_running_; j++) {
        // 检查暂停状态
        while (animation_paused_ && animation_running_) {
            vTaskDelay(pdMS_TO_TICKS(10));
            // 暂停期间更新时间基准，避免时间跳跃
            last_time = esp_timer_get_time() / 1000;
        }
        
        if (!animation_running_) break;
        
        // 计算当前帧的基础色调
        float base_hue = j * hue_step;
        
        // 批量设置所有LED颜色
        for (int i = 0; i < led_count_; i++) {
            // 计算每个LED的色调，形成彩虹渐变
            float led_hue = fmod(base_hue + i * led_hue_offset, 360.0f);
            Color rainbow_color = HSVtoRGB(led_hue, 1.0f, 1.0f);
            SetPixelNoRefresh(i, rainbow_color);
        }
        
        // 统一刷新显示
        esp_err_t refresh_ret = Refresh();
        if (refresh_ret != ESP_OK) {
            ESP_LOGW(TAG, "彩虹动画刷新失败: %s", esp_err_to_name(refresh_ret));
        }
        
        // 精确时间控制，补偿处理时间
        uint32_t current_time = esp_timer_get_time() / 1000;
        uint32_t elapsed = current_time - last_time;
        
        if (elapsed < step_delay) {
            uint32_t remaining_delay = step_delay - elapsed;
            vTaskDelay(pdMS_TO_TICKS(remaining_delay));
        }
        
        last_time = esp_timer_get_time() / 1000;
    }
    
    animation_running_ = false;
    current_animation_ = AnimationType::NONE;
    return ESP_OK;
}

// ==================== 新增动画效果实现 ====================

esp_err_t WS2812::Chase(const Color& color, int chase_length, uint32_t delay_ms) {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    // 参数验证和调整
    if (chase_length <= 0) {
        ESP_LOGW(TAG, "追逐长度%d无效，使用默认值3", chase_length);
        chase_length = 3;
    } else if (chase_length > led_count_) {
        ESP_LOGW(TAG, "追逐长度%d超过LED数量%d，已调整", chase_length, led_count_);
        chase_length = led_count_;
    }
    
    if (delay_ms == 0) {
        ESP_LOGW(TAG, "追逐延迟为0，使用默认值50ms");
        delay_ms = 50;
    }

    current_animation_ = AnimationType::CHASE;
    animation_running_ = true;
    animation_paused_ = false;
    
    // 计算追逐周期数：完整遍历一次 + 完全消失
    const int total_positions = led_count_ + chase_length;
    uint32_t last_time = esp_timer_get_time() / 1000;
    
    // 一个完整的追逐周期
    for (int pos = 0; pos < total_positions && animation_running_; pos++) {
        // 检查暂停状态
        while (animation_paused_ && animation_running_) {
            vTaskDelay(pdMS_TO_TICKS(10));
            // 暂停期间更新时间基准
            last_time = esp_timer_get_time() / 1000;
        }
        
        if (!animation_running_) break;
        
        // 清除所有LED（批量操作）
        for (int i = 0; i < led_count_; i++) {
            SetPixelNoRefresh(i, Color::BLACK);
        }
        
        // 设置追逐段，使用改进的渐变算法
        for (int i = 0; i < chase_length; i++) {
            int led_index = pos - i;
            if (led_index >= 0 && led_index < led_count_) {
                // 使用指数衰减创建更自然的拖尾效果
                float distance_factor = static_cast<float>(i) / chase_length;
                float brightness_factor = exp(-distance_factor * 2.0f); // 指数衰减
                
                // 确保最小亮度，避免完全消失
                brightness_factor = std::max(0.1f, brightness_factor);
                
                Color chase_color = color * brightness_factor;
                SetPixelNoRefresh(led_index, chase_color);
            }
        }
        
        // 统一刷新显示
        esp_err_t refresh_ret = Refresh();
        if (refresh_ret != ESP_OK) {
            ESP_LOGW(TAG, "追逐动画刷新失败: %s", esp_err_to_name(refresh_ret));
        }
        
        // 精确时间控制
        uint32_t current_time = esp_timer_get_time() / 1000;
        uint32_t elapsed = current_time - last_time;
        
        if (elapsed < delay_ms) {
            uint32_t remaining_delay = delay_ms - elapsed;
            vTaskDelay(pdMS_TO_TICKS(remaining_delay));
        }
        
        last_time = esp_timer_get_time() / 1000;
    }
    
    // 清除所有LED
    Clear();
    
    animation_running_ = false;
    current_animation_ = AnimationType::NONE;
    return ESP_OK;
}

esp_err_t WS2812::TheaterChase(const Color& color, uint32_t delay_ms) {
    if (!is_initialized_) {
        ESP_LOGE(TAG, "WS2812未初始化");
        return ESP_ERR_INVALID_STATE;
    }

    // 参数验证
    if (delay_ms == 0) {
        ESP_LOGW(TAG, "剧院追逐延迟为0，使用默认值100ms");
        delay_ms = 100;
    }

    current_animation_ = AnimationType::THEATER_CHASE;
    animation_running_ = true;
    animation_paused_ = false;
    
    // 优化循环次数：根据LED数量动态调整
    const int min_cycles = 5;
    const int max_cycles = 20;
    int cycles = std::max(min_cycles, std::min(max_cycles, led_count_ / 3));
    
    uint32_t last_time = esp_timer_get_time() / 1000;
    
    for (int cycle = 0; cycle < cycles && animation_running_; cycle++) {
        for (int offset = 0; offset < 3 && animation_running_; offset++) {
            // 检查暂停状态
            while (animation_paused_ && animation_running_) {
                vTaskDelay(pdMS_TO_TICKS(10));
                // 暂停期间更新时间基准
                last_time = esp_timer_get_time() / 1000;
            }
            
            if (!animation_running_) break;
            
            // 清除所有LED（批量操作）
            for (int i = 0; i < led_count_; i++) {
                SetPixelNoRefresh(i, Color::BLACK);
            }
            
            // 每隔3个LED点亮一个，创建追逐效果
            for (int i = offset; i < led_count_; i += 3) {
                // 添加轻微的亮度变化，使效果更生动
                float brightness_factor = 0.8f + (cycle % 3) * 0.1f; // 0.8-1.0
                Color chase_color = color * brightness_factor;
                SetPixelNoRefresh(i, chase_color);
            }
            
            // 统一刷新显示
            esp_err_t refresh_ret = Refresh();
            if (refresh_ret != ESP_OK) {
                ESP_LOGW(TAG, "剧院追逐刷新失败: %s", esp_err_to_name(refresh_ret));
            }
            
            // 精确时间控制
            uint32_t current_time = esp_timer_get_time() / 1000;
            uint32_t elapsed = current_time - last_time;
            
            if (elapsed < delay_ms) {
                uint32_t remaining_delay = delay_ms - elapsed;
                vTaskDelay(pdMS_TO_TICKS(remaining_delay));
            }
            
            last_time = esp_timer_get_time() / 1000;
        }
    }
    
    // 清除所有LED
    Clear();
    
    animation_running_ = false;
    current_animation_ = AnimationType::NONE;
    return ESP_OK;
}

// ==================== 颜色工具函数实现 ====================

WS2812::Color WS2812::HSVtoRGB(float h, float s, float v) {
    // 确保输入参数在有效范围内
    h = fmod(h, 360.0f);
    if (h < 0) h += 360.0f;
    s = std::max(0.0f, std::min(1.0f, s));
    v = std::max(0.0f, std::min(1.0f, v));
    
    float c = v * s;
    float x = c * (1 - abs(fmod(h / 60.0, 2) - 1));
    float m = v - c;
    
    float r, g, b;
    
    if (h >= 0 && h < 60) {
        r = c; g = x; b = 0;
    } else if (h >= 60 && h < 120) {
        r = x; g = c; b = 0;
    } else if (h >= 120 && h < 180) {
        r = 0; g = c; b = x;
    } else if (h >= 180 && h < 240) {
        r = 0; g = x; b = c;
    } else if (h >= 240 && h < 300) {
        r = x; g = 0; b = c;
    } else {
        r = c; g = 0; b = x;
    }
    
    return Color(
        static_cast<uint8_t>((r + m) * 255),
        static_cast<uint8_t>((g + m) * 255),
        static_cast<uint8_t>((b + m) * 255)
    );
}

WS2812::Color WS2812::Interpolate(const Color& from, const Color& to, float factor) {
    factor = std::max(0.0f, std::min(1.0f, factor)); // 限制在0-1范围内
    
    return Color(
        static_cast<uint8_t>(from.red + (to.red - from.red) * factor),
        static_cast<uint8_t>(from.green + (to.green - from.green) * factor),
        static_cast<uint8_t>(from.blue + (to.blue - from.blue) * factor)
    );
}

WS2812::Color WS2812::Wheel(uint8_t pos) {
    pos = 255 - pos;
    if (pos < 85) {
        return Color(255 - pos * 3, 0, pos * 3);
    }
    if (pos < 170) {
        pos -= 85;
        return Color(0, pos * 3, 255 - pos * 3);
    }
    pos -= 170;
    return Color(pos * 3, 255 - pos * 3, 0);
}

WS2812::Color WS2812::RandomColor() {
    return Color(
        esp_random() % 256,
        esp_random() % 256,
        esp_random() % 256
    );
}

// ==================== 私有辅助函数实现 ====================

WS2812::Color WS2812::ApplyBrightness(const Color& color) const {
    if (brightness_ == 100) {
        return color;
    }
    
    float factor = static_cast<float>(brightness_) / 100.0f;
    return color * factor;
}

void WS2812::DelayMs(uint32_t ms) const {
    vTaskDelay(pdMS_TO_TICKS(ms));
}

// ==================== 动画控制函数实现 ====================

void WS2812::StopAnimation() { 
    animation_running_ = false; 
    current_animation_ = AnimationType::NONE;
}

void WS2812::PauseAnimation() { 
    animation_paused_ = true; 
}

void WS2812::ResumeAnimation() { 
    animation_paused_ = false; 
} 